<!--
 * @Author: wjk
 * @Date: 2019-12-31 15:40:51
 * @LastEditors: wangzm
 * @LastEditTime: 2020-03-07 14:34:57
 * @description: file content
 -->
<template>
  <base-page-view :class-name="'search-container ' + (showResult ? 'list-background':'')">
    <view class="sticky-wrap">
      <view class="search-block">
        <view v-if="!authFlag" class="search-left">
          <search-bar ref="search-bar" background="#fff" :keyword="listQuery.keyword" :placeholder="placeholderText" @change="keyChange" @clear="keyClear" @search="search"></search-bar>
        </view>
      </view>
      <view v-if="platform_list && platform_list.length > 1" class="platform-block">
        <view v-for="(item, index) in platform_list" :key="index" class="platform-item" :class="{ active: listQuery.platform === item.platform }" @click="platformChange(item)">{{ item.name }}</view>
      </view>
      <block v-if="listQuery.keyword && showResult">
        <sort-bar ref="sortBar" :platform="listQuery.platform" :sort.sync="sortQuery" @change="handleSortChange" />
        <view v-if="listQuery.platform!=='VOP'" class="coup-tab">
          <view class="coup-tab-l">
            <image src="/static/images/commission/coupon_ico.png" class="icon" />
            <text class="txt">仅显示优惠券商品</text>
          </view>
          <view class="coup-tab-r tab-switch" :class="{'active': showCoup }" @click="handleSwitch">
            <text class="tab-switch-icon"></text>
          </view>
        </view>
      </block>
    </view>

    <template v-if="listQuery.keyword">
      <!-- 搜索结果 -->
      <view v-if="showResult" class="goods-list">
        <view v-for="(item, index) in list" :key="index" class="goods-item-container" @click="handleNavigeTo(item, index)">
          <view class="goods-pic">
            <b-image :src="item.imageUrl" width="260" height="260" mode="aspectFit" />
          </view>
          <view class="goods-info">
            <view class="goods-title">{{ item.title }}</view>
            <view v-if="listQuery.platform==='PDD'" class="goods-sales">销量{{ item.monthSales }}</view>
            <view class="goods-coup">
              <view v-if="item.hasCoupon || item.discount" class="coupon" :style="'background-image: url('+conpon_bg[listQuery.platform]+')'">
                <template v-if="item.hasCoupon">{{ item.couponDiscount }}元券</template>
                <template v-else-if="item.discount">{{ item.discount }}折</template>
              </view>
              <template>
                <text class="goods-coup-price-tip">赚{{ token?item.commission:item.diamondCommission | formatMoney }}元</text>
              </template>
            </view>
            <view class="goods-price">
              <text class="goods-price-num">{{ item.actualPrice }}</text>
              <text class="goods-price-tip">{{ listQuery.platform==='PDD' ? '券后价' : '折后价' }}</text>
            </view>
            <view class="goods-type">
              <b-image v-if="listQuery.platform==='VOP'" class-name="goods-type-icon" :src="'/static/images/biHuaSuan/icon_'+listQuery.platform+'.png'" mode="aspectFit" :is-asset="true" />
              <b-image v-else class-name="goods-type-icon" :src="'/static/images/biHuaSuan/platform_'+listQuery.platform+'.png'" mode="aspectFit" :is-asset="true" />
              <text class="goods-type-txt">{{ item.shopNick }}</text>
            </view>
          </view>
        </view>
        <base-list-state :list-length="listLength" :list-query="{page_no: listQuery.pageNum, page_size: listQuery.pageSize}" :list-state="listState" :list-empty="listEmpty" />
      </view>
    </template>
    <view v-else class="history-list">
      <!-- 热门搜索 -->
      <view v-if="keyword.hot.length" class="keyword-block hot">
        <view class="block-title">
          <view class="sub-item">热门搜索</view>
        </view>
        <view class="block-content">
          <view v-for="(item, index) in keyword.hot" :key="index" class="keyword-item" :class="{'icon': randColor(item)}" @click="keywordClick(item, 'hot')">
            {{ item }}
          </view>
        </view>
      </view>
      <!-- 搜索历史 -->
      <view v-if="keyword.history.length" class="keyword-block history">
        <view class="block-title">
          <view class="sub-item">历史记录</view>
          <image class="icon" src="/static/images/icon/icon_delete.png" mode="aspectFit" @click="clearHistory" />
        </view>
        <view class="block-content">
          <view v-for="(item, index) in keyword.history" :key="index" class="keyword-item" @click="keywordClick(item, 'history')">{{ item }}</view>
        </view>
      </view>
    </view>
  </base-page-view>
</template>

<script>
import searchBar from '@/components/searchBar/index'
import sortBar from './sortbar.vue'
import { debounce } from '@/utils/tools'
import './index.scss'
export default {
  components: {
    searchBar,
    sortBar
  },
  data() {
    return {
      platform_list: [],
      conpon_bg: {
        PDD: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/bg_coupon_PDD.png`,
        VOP: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/bg_coupon_VOP.png`
      },
      placeholderText: '搜索商品名或黏贴宝贝标题',
      keyType: '', // 埋点用, history、hot
      keyword: {
        history: uni.getStorageSync('bhsKeywords') || [],
        hot: []
      },
      sortQuery: {
        sortKey: '', // 佣金：commission，销量：sales ，价格：price
        sortValue: '', // ASC 正序/ DESC 逆序
        highPrice: '',
        lowPrice: ''
      },
      refreshFlag: false,
      listQuery: {
        cid: '',
        secondCid: '',
        filterCoupon: '0',
        highPrice: '',
        lowPrice: '',
        orderBy: '',
        juHuaSuan: '',
        keyword: '',
        pageId: '',
        pageNum: 1,
        pageSize: 10,
        platform: '', // ALI, PDD, JD, VOP, BIXUAN
        sortKey: '', // 佣金：commission，销量：sales ，价格：price
        sortValue: '', // ASC 正序/ DESC 逆序
        tagType: '',
        topicId: ''
      },
      list: [],
      listState: {
        loading: false,
        more: true
      },
      listEmpty: { type: 'empty_search', text: '没有搜索到相关的商品' },
      showResult: false,
      showCoup: false,
      authFlag: false
    }
  },
  computed: {
    listLength() { // 由于微信小程序无法自动更新base-list-state组件,故采用computed
      return this.list.length
    },
    randColor(index) {
      return function(index) {
        return this.randArr.includes(index)
      }
    }
  },
  onLoad(option) {
    // console.log(option)
    this.listQuery = {
      cid: '',
      secondCid: '',
      filterCoupon: '',
      highPrice: '',
      lowPrice: '',
      orderBy: '',
      juHuaSuan: '',
      keyword: '',
      pageId: '',
      pageNum: 1,
      pageSize: 10,
      platform: 'PDD', // ALI, PDD, JD, VOP, BIXUAN
      sortKey: '', // 佣金：commission，销量：sales ，价格：price
      sortValue: '', // ASC 正序/ DESC 逆序
      tagType: '',
      topicId: ''
    }
    this.listState = {
      loading: false,
      more: true
    }
    this.list = []
    uni.getStorage({
      key: 'clipDataSearch',
      success: (res) => {
        this.keywordClick(res.data)
        uni.removeStorage({ key: 'clipDataSearch' })
      }
    })

    this.fetchData()
    this.fetchPlatformData()
  },
  onShow() {
    if (this.authFlag) {
      this.authFlag = false
      this.fetchGoodsData(true)
    }
  },
  onPullDownRefresh() {
    this.listQuery.pageNum = 1
    this.fetchGoodsData(true)
  },
  onReachBottom: debounce(function() {
    if (this.listState.more && !this.listState.loading) {
      this.listQuery.pageNum++
      this.fetchGoodsData()
    }
  }, 500),
  methods: {
    // 获取热门搜索
    async fetchData() {
      const res = await this.$api.biHuaSuanApi.getSearchKey()
      if (res.success && res.data) {
        this.placeholderText = res.data.placeholder
        this.keyword.hot = res.data.hotSearchKeys || []
        // 随机显示热门搜索四个红色
        const len = this.keyword.hot.length
        this.randArr = []
        if (len > 0) {
          if (len <= 4) {
            for (let i = 0; i < len; i++) {
              this.randArr.push(i)
            }
          } else {
            const temArr = this.keyword.hot.slice(0)
            for (let i = 0; i < 4; i++) {
              const index = Math.floor((Math.random() * temArr.length))
              this.randArr.push(temArr.splice(index, 1)[0])
            }
          }
        }
      }
    },
    async fetchPlatformData() {
      const res = await this.$api.biHuaSuanApi.getSearchPlatform()
      if (res.success && res.data) {
        this.platform_list = res.data
        if (res.data && res.data.length) {
          this.listQuery.platform = res.data[0].platform
        }
      }
    },
    platformChange(item) {
      this.listQuery.platform = item.platform
      if (this.showResult) {
        this.$refs.sortBar.setIndex(0)
        this.search()
      }
    },
    handleSwitch() {
      this.showCoup = !this.showCoup
      if (this.showCoup) {
        this.listQuery.filterCoupon = '1'
      } else {
        this.listQuery.filterCoupon = '0'
      }
      this.list = []
      this.showResult = true
      this.listQuery.pageNum = 1
      this.listState.more = true
      this.fetchGoodsData()
    },
    clearHistory() {
      console.log(11)
      this.$gc.$message({
        content: '确认清空历史记录?',
        title: '提示',
        confirmColor: '#FFF', // 确认按钮颜色,
        confirmBackground: '#FF759F', // 确认按钮背景色
        confirmText: '确定',
        align: 'center',
        confirm: () => {
          this.keyword.history = []
          uni.removeStorage({ key: 'bhsKeywords' })
        }
      })
    },
    keyChange(value) {
      this.listQuery.keyword = value
      if (value === '') {
        this.showResult = false
      }
    },
    // 输入框文字清除
    keyClear() {
      this.listQuery.keyword = ''
      this.showResult = false
    },
    // 关联词 热门搜索  历史记录点击
    keywordClick(value, type) {
      this.listQuery.keyword = value
      this.$refs['search-bar'].setValue(value)
      this.search(type)
    },
    handleSortChange(sortQuery) {
      console.log(sortQuery)
      this.sortQuery = sortQuery
      this.listQuery = {
        ...this.listQuery,
        ...sortQuery,
        pageNum: 1
      }
      this.fetchGoodsData()
    },
    // 搜索
    search(type) {
      if (this.listQuery.keyword !== '') {
        this.keyType = type
        this.sortQuery = {
          sortKey: '', // 佣金：commission，销量：sales ，价格：price
          sortValue: '', // ASC 正序/ DESC 逆序
          highPrice: '',
          lowPrice: ''
        }
        this.list = []
        this.saveSearchHistory(this.listQuery.keyword)
        this.showResult = true
        this.listQuery.pageNum = 1
        this.listState.more = true
        this.fetchGoodsData()
      }
      // this.listQuery.keyword = value
    },
    async fetchGoodsData(flag) {
      this.refreshFlag = !!flag
      this.listState.loading = true
      const res = await this.$api.biHuaSuanApi.getGoods(this.listQuery)
      if (this.listQuery.pageNum === 1) {
        this.list = []
      }
      if (res.success && res.data) {
        // const list = (res.data.list || []).map(i => {
        //  return i
        // })
        this.list = this.list.concat((res.data.list || []))
        this.listState.more = this.listQuery.pageNum < res.data.total
      } else if (res.code === 1002 && this.listQuery.platform === 'PDD') {
        this.$gc.$message({
          title: '提 示',
          content: '请先前往拼多多进行授权',
          confirmText: '去授权',
          align: 'center',
          confirm: () => {
            // #ifdef H5
            this.authFlag = true
            window.open(res.msg, '_blank')
            window.addEventListener('pageshow', (e) => {
              this.authFlag = false
              this.fetchGoodsData(true)
            })
            // #endif

            // #ifdef MP-WEIXIN
            if (res.data) {
              uni.navigateToMiniProgram({
                appId: res.data.appId,
                path: res.data.url,
                extraData: {},
                success: (res) => {
                  // 打开成功
                  this.authFlag = true
                }
              })
            }
            // #endif
          }
        })
      }

      setTimeout(() => {
        this.listState.loading = false
        this.refreshFlag = false
        uni.stopPullDownRefresh()
      }, 500)
    },
    // 保留历史记录
    saveSearchHistory(value) {
      const index = this.keyword.history.findIndex(i => i === value)
      if (index > -1) {
        this.keyword.history.splice(index, 1)
      }
      this.keyword.history = [value].concat(this.keyword.history)
      uni.setStorage({
        key: 'bhsKeywords',
        data: this.keyword.history
      })
    },
    handleNavigeTo(item, index) {
      this.$navigateTo(`/pagesBHS/goods/index?goodsId=${item.goodsId}&platform=${item.platform}`)
    },
    backClick() {
      uni.navigateBack()
    }
  }
}
</script>
